package com.heima.search.service.Imp;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO dto) {
        log.info("开始插入搜索的历史记录");
        //0.远程获取行为
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getUserId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"远程调用失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        //1.查询mogo是否有搜索过的行为 有只更新时间
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("keyword").is(dto.getSearchWords()));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            //2.没有就新增
            ApUserSearch search = new ApUserSearch();
            search.setEntryId(behaviorEntry.getId());
            search.setKeyword(dto.getSearchWords());
            search.setCreatedTime(new Date());
            mongoTemplate.insert(search);
        }
        log.info("插入搜索的历史记录结束了");
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        dto.setUserId(user.getId());
        //0.远程获取行为
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getUserId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"远程调用失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();

        List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10), ApUserSearch.class);

        return ResponseResult.okResult(searchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO historySearchDto) {
        if(historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }

}
